class Solution {//leetcode1162——地图分析
private:
    int dx[4]={0,0,-1,1};
    int dy[4]={1,-1,0,0};
public:
    int maxDistance(vector<vector<int>>& grid) {
        int n=grid.size(),m=grid[0].size();
        vector<vector<int>> dist(n,vector<int>(m,-1));
        queue<pair<int,int>> q;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(grid[i][j]==1){
                    dist[i][j]=0;
                    q.push({i,j});
                }
            }
        }
        int ret=0;
        while(q.size()){
            auto [i,j]=q.front();
            for(int k=0;k<4;k++){
                int x=i+dx[k];
                int y=j+dy[k];
                if(x>=0&&x<n&&y>=0&&y<m&&dist[x][y]==-1){
                    dist[x][y]=dist[i][j]+1;
                    q.push({x,y});
                    ret=max(ret,dist[x][y]);
                }
            }
            q.pop();
        }
        return ret==0?-1:ret;
    }
};